import { uploadtoqiniu } from '@/api/friend.js'
import lrz from "lrz"
import moment from "moment"
import { emoje } from './constent.js'

/* 防抖函数 */
function debounce() {
  let time
  return function (time = 500, callback) {
    if (time) {
      clearTimeout(time)
    }
    time = setTimeout(() => {
      callback.apply(this, arguments)
    }, time)
  }
}
/* 深拷贝 */
function deepClone(obj) {
  if (typeof obj !== 'object' || typeof obj == null) {
    return obj
  }
  let result = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      //函数递归实现深层拷贝
      result[key] = deepClone(obj[key])
    }
  }
  return result
}
/* 节流函数 */
function throttle() {
  let lastTime = 0
  return function (func, interval) {
    if (new Date().getTime() - lastTime >= interval) {
      func.apply(this, arguments)
      lastTime = new Date().getTime()
    }
  }
}
/* 判断是否是手机端 */
function isMobile() {
  // 手机端
  let reg =
    /(phone|pad|iPhone|iPod|ios|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i;
  return reg.test(navigator.userAgent);
}
/* 七牛云上传 */
async function uploadqiniu(qiniuToken, uploadimglist, coverflagname = "") {
  let PromiseList = []
  /* 对数据进行压缩 和  上传七牛云*/
  for (let i = 0; i < uploadimglist.length; i++) {
    let item = uploadimglist[i];
    if (!(item?.raw instanceof File) && !(item instanceof File)) {
      continue;
    }
    try {
      let rst = await lrz(item?.raw ?? item)
      // 处理成功会执行
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      let filetype = ''
      if (rst.file.type === 'image/png') {
        filetype = 'png'
      } else {
        filetype = 'jpg'
      }
      // 重命名要上传的文件
      const keyname = (item?.iscover ? `-${coverflagname}-` : "") + moment().format('YYYYMMDDHHmmssss') + Number.parseInt(Math.random() * 1000, 10) + '.' + filetype
      const formdata = new FormData()
      formdata.append('file', rst.file)
      formdata.append('token', qiniuToken)
      formdata.append('key', keyname)
      PromiseList.push(uploadtoqiniu(formdata, config))

    } catch (error) {
      console.log(error);
      ElMessage({
        message: '上传照片错误',
        type: 'warning',
      })
    }
  }
  let ress = await Promise.all(PromiseList).then((result) => {
    return result
  }).catch((error) => {
    console.log(error)      // 失败了，打出 '失败'
  })
  return ress
}
/* 转化天数 */
function tonum(data) {
  if (typeof data == "string") {
    data = parseInt(data);
  }
  if ((data / 1000) < 1) {
    return data.toString();
  } else {
    return (data / 1000).toFixed(1).toString() + "K";
  }


}
/* 转化评论 */
function wrapcomment(data) {
  if (data instanceof Array) {
    let res = data.map(item => {
      let content = machemoji(item.content);
      return {
        id: item.id,
        content: content,
        createdAt: moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss"),
        commentstrs: item.commentstrs,
        usercover: item.usercover,
        username: item.username,
        usersiteurl: item.usersiteurl,
        fatherid: item.fatherid,
        fromname: item.fromname,
        fromid: item.fromid,
        forid: item.forid,
        isstrs: false
      }
    })
    let parent = res.filter(item => item.fatherid == "")
    let child = res.filter(item => item.fatherid != "")
    tochild(parent, child)
    function tochild(parent, child) {
      parent.forEach(p => {
        child.forEach(c => {
          if (c.fatherid == p.id) {
            if (!p.childen) {
              p.childen = [c]
            } else {
              p.childen.push(c)
            }
          }
        })
      })
    }
    return parent
  } else {
    return []
  }
}
/* 转化表情 */
function machemoji(data) {
  let reg = /\[(.+?)\]/g; //匹配[]内的内容，即表情包内容
  let emoji = ""
  let res = data
  let rearray = reg.exec(data)
  while (rearray) {
    for (let i = 0; i < emoje.length; i++) {
      let item = emoje[i]
      if (item.name == rearray[1]) {
        emoji = item.emoji
        res.replace(`[${rearray[1]}]`, emoji)
        res = res.replace(`[${rearray[1]}]`, emoji)
        rearray = reg.exec(data)
        break;
      }
    }
  }
  return res
}
/* 欢迎语句 */
function getWelcomeSay(nickName) {
  let res;
  if (!nickName) {
    res = "欢迎来到康的个人博客";
    return res;
  }
  const now = new Date().getHours();
  if (now >= 0 && now < 5) {
    res = `夜深了：${nickName}，早点休息！`;
  } else if (now >= 5 && now < 9) {
    res = `早上好：${nickName}，今天又是活力满满的一天！`;
  } else if (now >= 9 && now < 12) {
    res = `上午好：${nickName}，请合理安排时间摸鱼！`;
  } else if (now >= 12 && now < 14) {
    res = `中午好：${nickName}，小睡一会吧`;
  } else if (now >= 14 && now < 18) {
    res = `下午好：${nickName}`;
  } else if (now >= 18 && now < 20) {
    res = `傍晚好：${nickName}，记得按时吃饭`;
  } else if (now >= 20 && now < 22) {
    res = `晚上好: ${nickName}`;
  } else if (now >= 22) {
    res = `晚上好: ${nickName}，记得按时碎觉哦`;
  }
  return res;
}
function gettime(data) {
  data = parseFloat(data)
  
  if(data<60){
    data = parseInt(data)
    return `00:${data < 10 ? "0"+ data : data }`
  }else{
    let res = ""
    let minute= Math.floor(data / 60)
    let s = parseInt(data % 60)
    res = `${minute < 10 ? "0"+ minute : minute}:${s < 10 ? "0"+s:s}`
    return res 
  }
}
export {
  debounce,
  throttle,
  isMobile,
  uploadqiniu,
  tonum,
  deepClone,
  wrapcomment,
  getWelcomeSay,
  gettime
}